//
//  RefreshView.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/22.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit

class HomeRefreshControl: UIRefreshControl {
    
    override init() {
        super.init()
        backgroundColor = UIColor.white
        
        addSubview(refreshView)
        refreshView.snp.makeConstraints { (maker) in
            maker.size.equalTo(CGSize(width: 150, height: 50))
            maker.center.equalTo(self)
        }
        
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.new, context: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        removeObserver(self, forKeyPath: "frame")
    }
    
    /// 箭头选择标记
    var rotationFlag = false
    // MARK:- 内部控制方法
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    
    
    /// 监听fram属性的改变
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        for view in subviews{
            if type(of: view) != type(of: refreshView) {
                view.removeFromSuperview()
            }
        }
        
        if frame.size.height == 60 && frame.origin.y == 0 {
            return
        }
        
        if isRefreshing {
            refreshView.startLoading()
            
        } else {
            
            if frame.origin.y < -55 && !rotationFlag{
                
                refreshView.arrowRotation(flag: rotationFlag)
                rotationFlag = true
            }
            
            if frame.origin.y > -55 && rotationFlag{
                
                refreshView.arrowRotation(flag: rotationFlag)
                rotationFlag = false
            }
            
        }
        
    }
    
    // MARK:- 懒加载
    private lazy var refreshView: RefreshView = RefreshView.refreshView()
}


class RefreshView: UIView {
    /// 箭头
    @IBOutlet weak var arrowImageView: UIImageView!
    /// 刷新提示
    @IBOutlet weak var refreshLbale: UILabel!
    /// 顶部View
    @IBOutlet weak var topView: UIView!
    /// loadingView
    @IBOutlet weak var loadingImageView: UIImageView!
    /// loadingLable
    @IBOutlet weak var loadingLable: UILabel!
    
    ///快速通过xib 加载一个view
    class func refreshView() -> RefreshView{
        return Bundle.main.loadNibNamed("RefreshView", owner: nil, options: nil)?.last as! RefreshView
    }

    //MARK:- 外部控制方法
    /// 箭头转向
    func arrowRotation(flag: Bool){
        
        refreshLbale.text = !flag ?  "松开刷新数据" : "下拉刷新..." 
        
        UIView.animate(withDuration: 0.25) {
            self.arrowImageView.transform = !flag ? CGAffineTransform(rotationAngle: CGFloat(Double.pi - 0.01)) : CGAffineTransform.identity
            }
    }
    
    /// 刷新界面显示 loadingView 开始旋转
    func startLoading() {
        topView.isHidden = true
        loadingImageView.isHidden = false
        loadingLable.isHidden = false
        
        if loadingImageView.layer.animation(forKey: "loading") != nil {
            return
        }
        
        let basicA = CABasicAnimation(keyPath: "transform.rotation")
        basicA.toValue = Double.pi * 2
        basicA.duration = 0.5
        basicA.repeatCount = MAXFLOAT
        basicA.isRemovedOnCompletion = false
        
        loadingImageView.layer.add(basicA, forKey: "loading")
        
    }
    
    /// 刷新界面隐藏 loadingView 动画移除
    func stopLoading() {
        topView.isHidden = false
        loadingImageView.isHidden = true
        loadingLable.isHidden = true
        loadingImageView.layer.removeAllAnimations()
    }

}
